/**
 * 
 */
package anyware.common.restlet.resource;

import java.util.Calendar;
import java.util.Date;

import org.restlet.Directory;
import org.restlet.Filter;
import org.restlet.data.Form;
import org.restlet.data.Request;
import org.restlet.data.Response;

/**
 * Special filter for serving {@link Directory} pointing to gwt folder. This
 * filter mainly adds catch control response header onto cachable get resources.
 * <ul>
 * <li>Header <code>Pragma: no-cache</code> will be added on resource of GWT
 * {@code xxx.nocache.js}, also its expiration date will be set to
 * <code>NOW</code>. </li>
 * <li>Header <code>Cache-control:max-age=31536000</code> will be added on
 * other cachable resources; and its expiration date will be set to next year.</li>
 * </ul>
 * 
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 103 $
 * @version 0.0.2
 */
public class GWTFolderFilter extends Filter {

    @Override
    protected void afterHandle(final Request request, final Response response) {
        super.afterHandle(request, response);
        Form form = (Form) response.getAttributes().get(
                "org.restlet.http.headers");
        if (form == null) {
            form = new Form();
            response.getAttributes().put("org.restlet.http.headers", form);
        }
        if (response.getEntity() != null) {
            if (request.getResourceRef().getPath().indexOf(".nocache.") != -1) {
                form.set("Pragma", "no-cache", true);
                response.getEntity().setExpirationDate(new Date());
            } else {
                form.set("Cache-Control", "max-age=31536000", true);
                final Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.YEAR, 1);
                response.getEntity().setExpirationDate(calendar.getTime());
            }
        }
    }
}
